define(function(require, exports, module){
	
	/**
     * @name popPosition
     * @class 封装 新建add 编辑edit 删除del 流量分片。
     */
	
	var requestUrl = {
			create: '/trp/resource/create/',
			edit: '/trp/resource/update/',
			del: '/trp/resource/delete/',
			get: '/trp/resource/get/',
			getArea: '/trp/strategy/get_areas_tree/'
		},
		tmpl = ['<div class="pop-form pop-createresource">',
		        	'<form class="resourceForm">',
		    		'<div class="form_item hasunit">',
		    			'<label class="form_label">日期：</label>',
		    			'<div class="form_ctrl strategy_date">',
		    				'<div class="daterangebox">',
		    			        '<input type="text" name="circle" class="form-control daterangebox-ipt required" style="width:234px;" readonly placeholder="请选择日期..." />',
		    			        '<a class="daterangebox-btn" href="javascript:;">日期</a>',
		    			    '</div>',
		    			'</div>',
		    		'</div>',
		    		'<div class="form_item hasunit" style="height:auto;">',
		    			'<label class="form_label">时间定向：</label>',
		    			'<div class="form_ctrl gettimedata"><input name="times" class="required" type="hidden"></div>',
		    		'</div>',
		    		'<div class="form_item">',
		    			'<label class="form_label">地域定向：</label>',
		    			'<div class="form_ctrl">',
		    				'<input type="text" name="areas" class="form-control required getareadata" placeholder="请选择地域..."/>',
		    				'<div class="areatree"></div>',
		    			'</div>',
		    		'</div>',
		    		'<div class="form_item hasunit">',
		    			'<label class="form_label">独占者：</label>',
		    			'<div class="form_ctrl types">',
		    				'<input type="text" name="org" class="required" placeholder="请选择独占者..." style="width:234px;"/>',
		    			'</div>',
		    		'</div>',
		    		'<div class="form_item hasunit">',
		    			'<label class="form_label">独占花费：</label>',
		    			'<div class="form_ctrl">',
		    				'<input type="text" name="cost" class="form-control required number" style="display:inline-block;" placeholder="请填写花费..." />',
		    				'&nbsp;元',
		    			'</div>',
		    		'</div>',
		    	'</form>',
		    '</div>'].join('');
	
	/* 分片资源弹框 */
	var popResource = function(option, isedit){
		var op = $.extend({
			id: '',
			url: '',
			start: '',
			end: '',
			min: '',
			max: ''
		}, option);
		
		if(semi.utils.isEmpty(op.id) || semi.utils.isEmpty(op.url))return;
		
		var areaArr = { submitNode:[], nodes:[], parents:[], data:[]}, timeArr = [];
		$dialog({
            title: op.title || '流量分片',
            width: '600px',
            zIndex: 80,
            onshow: function(){
        		var $d = this, $node = $(this.node);
        		var initDialog = function(){
        			//日期
        			$('.daterangebox-ipt',$node).daterangepicker({
        				startDate: op.start,
        				endDate: op.end,
        				minDate: op.min,
        				maxDate: op.max,
	    	            format:'YYYY-MM-DD'
	    	        }, function(start, end, label) {});
        			
        			//地域定向	areaArr = {submitNode:[], nodes:[], parents:[], data:[]}
            		$('.getareadata',$node).on('click', function(){
            			var treeDlgOpened = false;
            			var $areaDlg = $dialog({
            				title: '地域定向',
            				width: '400px',
            				zIndex: 87,
            				onshow: function(){
            					var _$d = this, _$node = $(this.node);
            					var _initTree = function(){
            						require.async('ztree', function(){
            							var _treeData = semi.utils.clone(areaArr.data);
            							// 初始化选中
            							$.each(areaArr.submitNode, function(i,n){
            								var _index = -1;
            								$.each(_treeData, function(j,m){
        										if(n.id==m.id)_index = j;
        									});
            								if(_index==-1)return;
            								$.each(_treeData, function(j,m){
            									if(m.pId==n.id){
            										$.each(_treeData, function(k,o){
            											if(o.pId==m.id){
            												$.extend(o,{
            													checked: true
            												});
            											}
            										});
            										$.extend(m,{
            											checked: true
            										});
            									}
            								});
            								$.extend(_treeData[_index],{
            									checked: true
            								});
                                		});
            							// 初始化展开
            							$.each(_treeData, function(i,n){
        									var len = 0; sub = 0;
        									$.each(_treeData, function(j,m){
        										if(m.pId==n.id){
        											if(m.checked){
        												sub++;
        											}
        											len++;
        										}
        									});
        									if(sub!=0){
        										$.extend(n,{
        											open: true,
        										});
        									}
        									if(len==sub){
        										$.extend(n,{
        											open: false,
        										});
        									}
            							});
            							//展开[中国]
            							$.extend(_treeData[0],{
            								open: true
            							});
            							
            							_$d.content('<div style="width:400px;height:300px;overflow:auto;"><input type="text" class="form-control ipt_search" placeholder="模糊搜索" style="position:absolute;top:-60px;left:140px;"/><ul id="areaTree" class="ztree"></ul></div>');
        								$.fn.zTree.init($('#areaTree'), {
        									data: {
    											simpleData: {
    												enable: true
    											}
    										},
                							view: {
                								fontCss: function(treeId, treeNode) {
                									return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
                								}
                							},
                							check: {
                								enable: true,
                								autoCheckTrigger: true
                							}
                						}, _treeData);
        								
        								/* 模糊搜索 */
                						var treeObj = $.fn.zTree.getZTreeObj('areaTree'),
                							lastValue = '',
                							nodeList = [],
                							updateNodes = function(highlight) {
                    							for( var i=0, l=nodeList.length; i<l; i++) {
                    								nodeList[i].highlight = highlight;
                    								treeObj.updateNode(nodeList[i]);
                    								treeObj.expandNode(nodeList[i].getParentNode(), true, false, false);
                    							}
                    						};
                						
                						$('.ipt_search',_$node).on({
                							keyup: function(){
                    							var value = $(this).val().trim(),
                    								keyType = 'name';
                    							
                								if(lastValue === value) return;
                								lastValue = value;
                								updateNodes(false);
                								if(semi.utils.isEmpty(value)) return;
                								nodeList = treeObj.getNodesByParamFuzzy(keyType, value);
                    							updateNodes(true);
                    						}
                						});
    								});
            					}
            					if(semi.utils.isEmpty(areaArr.data)){
            						$ajax.ajax({
            							url: requestUrl.getArea,
            							success: function(treedata){
            								areaArr.data = treedata.data;
            								areaArr.data[0].pId = null;
            								_initTree();
            							}
                					});
            					}else{
            						_initTree();
            					}
            				},
            				okValue: '确定',
            				ok: function(){
                        		var treeObj = $.fn.zTree.getZTreeObj('areaTree'),
									checkedNodes = treeObj.getCheckedNodes();
                        		
                        		areaArr.submitNode = [], areaArr.nodes = [], areaArr.parents = [];
                        		$.each(checkedNodes, function(i,treeNode){
                        			var pNode = treeNode.getParentNode() , 
                        				node = {id:treeNode.id, name:treeNode.name, pId:treeNode.pId, parent:-1};
                    				if(!semi.utils.isEmpty(pNode)){
                    					node.parent = pNode.id;
                    					areaArr.parents.pushOnly(pNode);
                    				}
                    				areaArr.nodes.pushOnly(node);
                    				areaArr.submitNode.pushOnly({id:treeNode.id, name:treeNode.name});
                        		});
                        		if(semi.utils.isEmpty(areaArr.nodes))areaArr.parents = [];
                        		$.each(areaArr.parents, function(i,n){
                        			var length = 0;
                        			$.each(areaArr.nodes, function(j,m){
                            			if(m.parent==n.id)length++;
                            		});
                        			if(length==n.children.length){
                        				var allchecked = true;
                        				$.each(n.children, function(j,m){
                        					if(!semi.utils.isEmpty(m.children)){
                                    			$.each(m.children, function(k,o){
                                        			if(!o.checked)allchecked = false;
                                        		});
                                			}
                        				});
                        				if(allchecked){
                        					$.each(areaArr.nodes, function(j,m){
                                    			if(m.parent==n.id){
                                    				areaArr.submitNode.remove({id:m.id, name:m.name});
                                    			}
                                    		});
                        				}else{
                        					areaArr.ids.remove(n.id);
                                			areaArr.names.remove(n.name);
                        				}
                        			}else{
                        				areaArr.submitNode.remove({id:n.id, name: n.name});
                        			}
                        		});
                        		
                        		var _nameArr = [];
                        		$.each(areaArr.submitNode, function(i,n){
                        			_nameArr.push(n.name);
                        		});
                        		$('.getareadata',$node).val(_nameArr.join('，'));
                            },
                            cancelValue: '取消',
                            cancel: true
            			}).showModal();
            		});
            		
            		//时间定向
            		var _hours = [];
            		for(var i=0; i<4; i++){
            			$('.gettimedata [name=times]',$node).before('<div class="checktime" style="height:24px;position:relative;"><div class="btn-group btn-group-xs" style="display:inline-block;"></div><input type="checkbox" name="checktime" style="width:auto;position:absolute;right:-20px;top:7px;"></div>');
            			for(var j=0; j<6; j++){
            				$('.gettimedata .btn-group:last',$node).append('<button type="button" class="btn btn-default btn-info" time="'+(j+i*6)+'" style="width:50px;">'+(j+i*6)+':00</button>');
            				_hours.pushOnly(j+i*6);
            			}
            		}
            		if(semi.utils.isEmpty(timeArr)){
            			timeArr = _hours;
            		}else{
            			$('.gettimedata [time]',$node).removeClass('btn-info');
            			$.each(timeArr, function(i,n){
            				$('.gettimedata [time='+n+']',$node).addClass('btn-info');
            			});
            		}
            		
            		$('.checktime',$node).each(function(){
            			var $this = $(this);
            			if($('.btn-info',$this).size()==$('.btn-default',$this).size()){
            				$('[name=checktime]',$this)[0].checked = true;
            			}else{
            				$('[name=checktime]',$this)[0].checked = false;
            			}
            		});
            		$('.gettimedata [name=times]',$node).val(timeArr.join(''));
            		
            		$('.checktime [name=checktime]',$node).on('change', function(){
            			var $checktime = $(this).parents('.checktime:first');
            			if($(this)[0].checked){
    			    		$('.btn-default',$checktime).each(function(){
    			    			$(this).addClass('btn-info');
    			    			timeArr.pushOnly(parseInt($(this).attr('time')));
    			    		});
    			    	}else{
    			    		$('.btn-default',$checktime).each(function(){
    			    			$(this).removeClass('btn-info');
    			    			timeArr.remove(parseInt($(this).attr('time')));
    			    		});
    			    	}
            			$('.gettimedata [name=times]',$node).val(timeArr.join('')).siblings('label.error').remove();
            		});
            		$('.gettimedata .btn',$node).click(function(){
            			var t = parseInt($(this).attr('time'));
            			if($(this).hasClass('btn-info')){
            				$(this).removeClass('btn-info');
            				timeArr.remove(t);
            			}else{
            				$(this).addClass('btn-info');
            				timeArr.pushOnly(t);
            			}
            			$('.gettimedata [name=times]',$node).val(timeArr.join('')).siblings('label.error').remove();
            			$('.checktime',$node).each(function(){
                			var $this = $(this);
                			if($('.btn-info',$this).size()==$('.btn-default',$this).size()){
                				$('[name=checktime]',$this)[0].checked = true;
                			}else{
                				$('[name=checktime]',$this)[0].checked = false;
                			}
                		});
            		});
            		$('.gettimedata',$node).height($('.gettimedata',$node).height()-29);
            		
            		//独占者
            		var orgdata = $('[name=org]',$node).data('data');
            		$('[name=org]',$node).attr('disabled','disabled');
            		$ajax.ajax({
            			url: '/trp/resource/get_organizations/',
            			success: function(data){
            				$('[name=org]',$node).removeAttr('disabled').select2({
                            	data: {results: data.bodyData}
                            }).on('select2-selecting', function(event){
                    			$(this).siblings('label.error').remove();
                    			if(event.object.type==0){
                    				$('[name=cost]',$node).val(0).attr('disabled','disabled');
                    			}else{
                    				$('[name=cost]',$node).val(0).removeAttr('disabled','disabled');
                    			}
                    		}).on('select2-open', function(){
								$(this).removeClass('error').siblings('label.error').remove();
							});
            				if(!semi.utils.isEmpty(orgdata)){
                				$('[name=org]',$node).select2('val', orgdata.id)
                    		}
            			}
            		});
        		}
        		
        		$d.content(tmpl);
        		
        		if(!semi.utils.isEmpty(isedit) && isedit && !semi.utils.isEmpty(op.data)){
        			$('.daterangebox-ipt',$node).val(op.data.start + ' 至 '+ op.data.end);
        			
        			//地域定向
            		var _areasName = [];
            		$.each(op.data.areas, function(i,n){
            			areaArr.submitNode.push({id:n.id, name:n.name});
            		});
					$.each(op.data.areas, function(i,n){
						_areasName.push(n.name);
					});
					$('.getareadata',$node).val(_areasName.join('，'));
        			
        			//时间定向
        			timeArr = op.data.hours;
        			
        			$('[name=org]',$node).data('data',{id:op.data.org_id, text: op.data.org_name});
        			
        			$('[name=cost]',$node).val(op.data.cost);
        		}
        		
        		$node.initUI();
        		initDialog();
        	},
        	okValue: '确定',
        	ok: function(){
        		var $d = this, $node = $(this.node);
        		if(!$('form',$node).valid())return false;
        		var range = $('[name=circle]',$node).val().split(' 至 '), _ares = [];
        		$.each(areaArr.submitNode, function(i,n){
        			_ares.push(n.id);
				});
        		$ajax.ajax({
        			url: op.url,
        			data: JSON.stringify({
        				traffic: op.id,
        				resource: op.id,
        				start: range[0],
        				end: range[1],
        				hours: timeArr,
        				org: $('[name=org]',$node).val(),
        				areas: _ares,
        				cost: $('[name=cost]',$node).val()
        			}),
            		contentType : "application/json",
                    type : 'POST',
                    dataType : 'json',
        			success: function(data){
    					$d.close().remove();
    					$dialog.alert((isedit?'修改':'新建')+'流量分片成功！','success');
    					if(!semi.utils.isEmpty(op.success) && $.isFunction(op.success))op.success.call(this, op);
        			},
        			error: function(data){
        				var message = (isedit?'修改':'新建')+'流量分片失败';
        				if(!semi.utils.isEmpty(data) && !semi.utils.isEmpty(data.message))message += ('：<b>'+data.message+'</b>');
        				$dialog.alert(message+'，请稍后重试！','warning');
        				if(!semi.utils.isEmpty(op.error) && $.isFunction(op.error))op.error.call(this, op);
        			}
        		});
            	return false;
            },
            cancelValue: '取消',
            cancel: true
        	
        }).showModal();
	}
	
	/* 新建流量分片 */
	var createResource = function(option){
		var op = $.extend({
			id: '',
			title: '新建流量分片',
			url: requestUrl.create,
			start: '',
			end: '',
			min: '',
			max: ''
		}, option);
		
		if(semi.utils.isEmpty(op.id))return;
		
		popResource(op, false);
	}
	
	/* 编辑流量分片 */
	var editResource = function(option){
		var op = $.extend({
			id: '',
			title: '编辑流量分片',
			url: requestUrl.edit,
			geturl: requestUrl.get,
			start: '',
			end: '',
			min: '',
			max: ''
		}, option);
		
		if(semi.utils.isEmpty(op.id))return;
		
		$ajax.ajax({
			url: op.geturl,
			data: {
				resource: op.id
			},
			success: function(data){
				popResource($.extend(op,{data:data}), true);
			},
			error: function(){
				$dialog.alert('获取流量分片信息失败，请稍后重试！','warning');
			}
		});
	}
	
	/* 删除流量分片 */
	var delResource = function(option){
		var op = $.extend({
			id: '',
			url: requestUrl.del,
			isdel: false,
			success: null,
			error: null
		}, option),
		title = (op.isdel?'删除':'停止');
		
		if(semi.utils.isEmpty(op.id))return;
		
    	var $dlg = $dialog.confirm({
    		title: title+'流量分片',
            content: '您确定要'+title+'该流量分片吗？',
            ok: function(){
            	var $dlg = this, op = $dlg.op;
            	$ajax.ajax({
                	url: op.url,
                    data: {
                    	resource: op.id
    				},
                    success: function(){
                    	$dlg.close().remove();
                    	$dialog.alert(title+'流量分片成功！','success');
                    	if(!semi.utils.isEmpty(op.success) && $.isFunction(op.success))op.success.call(this, op);
                    },
                    error: function(){
                    	$dlg.close().remove();
                    	$dialog.alert(title+'流量分片失败，请稍后重试！','warning');
                    	if(!semi.utils.isEmpty(op.error) && $.isFunction(op.error))op.error.call(this, op);
                    }
                });
            	return false;
            }
    	});
    	$.extend($dlg,{op:op});
	}
	
	return{
		create: createResource,
		edit: editResource,
		del: delResource
	}
});